﻿using System.Linq;
using System.Threading;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Noria.Web.Utility;
using MmContext = Noria.Web.MyMSDN.Models.MmContext;

namespace Noria.Web.MyMSDN
{
    /// <summary>
    /// Summary description for family
    /// </summary>
    public class FamilyHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            // test
            //Thread.Sleep(2000);

            var familyId = long.Parse(context.Request.QueryString["id"]);
            var locale = context.Request.QueryString["locale"];

            using (var db = new MmContext())
            {
                var family = db.Families.Include("Files").FirstOrDefault(p => p.FamilyId == familyId);
                if (family == null)
                {
                    throw new ServerException("The request product family doesn't exist.");
                }


                var files = family.Files
                                  .Where(p => p.Locale == locale || p.Locale == "mu")
                                  .OrderByDescending(p => p.PostedDate).ToArray();
                var payload = JArray.FromObject(files).ToString(Formatting.None);

                context.Response.ContentType = "application/json";
                context.Response.Write(payload);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}